package com.dd.edu.flashsale.portal.service;

import com.alibaba.fastjson.JSON;
import com.dd.edu.flashsale.portal.entity.Order;
import com.dd.edu.flashsale.portal.entity.OrderStatus;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

@Service
public class OrderService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate<String, Integer> redisTemplate;

    private final static String MQ_FLASHSALE_ORDER = "tp_flashSale";
    public final static String REDIS_GOODS_COUNT = "ms_goods_count";

    public boolean createOrder(Order order) {

        order.setOrderId(UUID.randomUUID().toString());
        order.setOrderStatus(OrderStatus.NEW);

        // 获取库存，库存减一
        Integer goodsCount = redisTemplate.opsForValue().get(REDIS_GOODS_COUNT);
        if (Objects.isNull(goodsCount) || goodsCount <= 0) {
            return false;
        }
        System.out.println("开始扣减库存");
        // 同步发送
        SendResult sendResult = rocketMQTemplate.syncSend(MQ_FLASHSALE_ORDER, order);
//        System.out.println(JSON.toJSON(sendResult));
        if (SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            System.out.println("库存扣减成功");
            redisTemplate.opsForValue().decrement(REDIS_GOODS_COUNT); // -1
        }
//        异步发送
//        rocketMQTemplate.asyncSend(MQ_FLASHSALE_ORDER, order, new SendCallback() {
//            @Override
//            public void onSuccess(SendResult sendResult) {
//                System.out.println("库存扣减成功");
//                redisTemplate.opsForValue().decrement(REDIS_GOODS_COUNT); // -1
//            }
//            @Override
//            public void onException(Throwable throwable) {
//            }
//        });

        return true;
    }
}
